import string

from kivy.logger import Logger

from amgineirc.viewModel.viewModel import ViewModel

class TrustedViewModel(ViewModel):
    
    good_chars = string.letters + string.digits + '_'
    
    def __init__(self, view, appdata):
        appdata['trusted_vm'] = self
        ViewModel.__init__(self, view)
        self._appdata = appdata
        itr = appdata['trusted_users'].data.iteritems()
        for n, v in itr:
            self.view.vm_add_trusted(v['nick'], v['real_name'], v['server'], v['rule_name'])
        view.vm_option_command_handler = self.handle_option_command
        
    def handle_editor_command(self, command, key, nick, real_name, server, rule_name):
        from amgineirc.view.settings.trustedView import TrustedView
        msg = []
        users = self._appdata['trusted_users'].data.keys()
        is_new = key not in users
        if command == TrustedView.submit_command:
            if len(nick) == 0:
                msg.append('Nick is required.')
            else:
                bad_letters = False
                for i in nick:
                    if i not in TrustedViewModel.good_chars:
                        msg.append("The Nick must only be letters, digits and '_'.")
                        bad_letters = True
                        break
                if bad_letters is False:
                    if len(key) == 0 and nick in self._appdata['trusted_users'].data:
                        msg.append("The Nick '%s' has already been added." % (nick))
            if len(server) == 0:
                msg.append('Server is required.')
            # check for settings folder
            if not self._appdata['trusted_users'].have_configuration_folder():
                msg.append(self._appdata['trusted_users'].missing_configuration_folder_message)
            ok = len(msg) == 0
            if ok:
                backup = self._appdata['trusted_users'].backup()
                if is_new:
                    ok = self._appdata['trusted_users'].add_user(nick,
                                                                 real_name,
                                                                 server,
                                                                 rule_name)
                    if ok is False:
                        msg.append('Unable to add your record because one already exists for that nick and server.')
                else:
                    ok = self._appdata['trusted_users'].set_user(nick,
                                                                 real_name,
                                                                 server,
                                                                 rule_name)
                    if ok is False:
                        msg.append('Unable to update your record because it does not already exist.')
                ok, smsg = self._appdata['trusted_users'].save()
                if ok is True:
                    if is_new:
                        self.view.vm_show_trusted_added(nick, real_name, server, rule_name)
                    else:
                        self.view.vm_show_trusted_edited(nick, real_name, server, rule_name)
                    # update the server and channel views
                    self._appdata['connection_vm'].update_user_lists(nick, server, True)
                else:
                    self._appdata['trusted_users'].restore(backup)
                    
                msg.append(smsg)
        return (ok, "\n".join(msg))
        
    def handle_confirm_delete(self, truefalse, nick, server):
        # the user has confirmed wanting to delete a trusted nick record
        key = nick.strip() + ':' + server.strip()
        if truefalse is True and key in self._appdata['trusted_users'].data:
            # check for settings folder
            ok = self._appdata['trusted_users'].have_configuration_folder()
            if not ok:
                smsg = self._appdata['trusted_users'].missing_configuration_folder_message
            else:
                backup = self._appdata['trusted_users'].backup()
                self._appdata['trusted_users'].del_user(nick, server)
                ok, smsg = self._appdata['trusted_users'].save()
                if not ok:
                    self._appdata['trusted_users'].restore(backup)
            if ok:
                self.view.vm_show_trusted_deleted(nick, server)
                # update the channel views
                self._appdata['connection_vm'].update_user_lists(nick, server, False)
            else:
                self.view.message_warn(smsg)

    def handle_option_command(self, command, nick, server):
        # a trusted is identified by (nick, server)
        from amgineirc.view.settings.trustedView import TrustedView, EditTrustedPopup 
        rule_options = self._appdata['rules'].data[:]
        rule_options.sort()
        server_options = self._appdata['servers'].data.keys()
        server_options.sort()
        if command == TrustedView.edit_command:
            record = self._appdata['trusted_users'].get_user(nick, server)
            if record is None:
                record = self._appdata['trusted_users'].default_record
            popup = EditTrustedPopup(command,
                                     nick,
                                     record['real_name'],
                                     server,
                                     server_options,
                                     record['rule_name'],
                                     rule_options,
                                     self.handle_editor_command)
            popup.open()
        elif command == TrustedView.delete_command:
            self.view.question_yes_no('Delete a Trusted Nick Record.',
                                      'Are you sure you want to permanently delete the trusted nick record for %s at %s?' % (nick, server),
                                      self.handle_confirm_delete,
                                      *(nick, server))
        elif command == TrustedView.create_command:
            record = self._appdata['trusted_users'].default_record
            popup = EditTrustedPopup(command,
                                     record['nick'],
                                     record['real_name'],
                                     record['server'],
                                     server_options,
                                     record['rule_name'],
                                     rule_options,
                                     self.handle_editor_command)
            popup.open()
